﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace LevenBlog.Core.Entities
{
    public static class EntityTypeCache
    {
        private static Dictionary<Type, TableInfo> cache = new Dictionary<Type, TableInfo>();
        //private static readonly object _synLock = new object();
        private static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();

        public static TableInfo Get<EntityType>()
            where EntityType : IEntity
        {
            Type type = typeof(EntityType);
            return Get(type);
        }

        public static TableInfo Get(Type type)
        {
            TableInfo find;
            //lock (_synLock) {
            //    if (!cache.TryGetValue(type, out find)) {
            //        find = null;
            //    }
            //}
            cacheLock.EnterReadLock();
            if (!cache.TryGetValue(type, out find)) {
                find = null;
            }
            cacheLock.ExitReadLock();
            return find;
        }

        public static TableInfo Get(IEntity entity)
        {
            Type type = entity.GetType();
            return Get(type);
        }

        public static void Insert(IEntity entity, TableInfo info)
        {
            Type type = entity.GetType();
            Insert(type, info);
        }

        public static void Insert(Type type, TableInfo info)
        {
            //lock (_synLock) {
            //    if (cache.ContainsKey(type))
            //        return;
            //    cache.Add(type, info);
            //}
            cacheLock.EnterWriteLock();
            cache[type] = info;
            cacheLock.ExitWriteLock();
        }
    }
}
